<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/6/8
 * Time: 10:22
 */

namespace app\service;


use think\Db;

class DingdingServer
{

    private $API_URL = "https://oapi.dingtalk.com/robot/send?access_token=";

    public function __construct() {

    }

    /**
     *
     * @param array $data
     * @param string $msgtype  text  link markdown actionCard
     * @return boolean
     */
    public function robotSend($data ) {
        $data = array ('msgtype' => 'text','text' => array ('content' => $data));
        $data_string = json_encode($data);
        //$result = $this->request_by_curl($data_string);
        return true;//$result;
    }

    function request_by_curl( $post_string) {

        $property_id=Myc('id');
        //$secret=Db::name('property')->where('id='.$property_id)->field('dingtalk,dingtalk_access_token')->find();
        $secret=array();
        $url = $this->API_URL.$secret['dingtalk_access_token'];
        $secret=$secret['dingtalk'];
        $time = time() *1000;
        $sign = hash_hmac('sha256', $time . "\n" . $secret,$secret,true);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        $url = "{$url}&timestamp={$time}&sign={$sign}";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}